/*
   Copyright (C) 2022 Ivan Polyakov

   This file is part of fltube.

   fltube is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   fltube is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
   
   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

#include "GridBrowser.hxx"

using namespace fltube;

GridBrowser::GridBrowser(int x, int y, int w, int h)
    : Fl_Scroll(x, y, w, h)
{
    type(VERTICAL);
}

void GridBrowser::AutoArrange()
{
    RearrangeChildren(x(), y(), w(), h());
    Fl_Scroll::redraw();
}

void GridBrowser::draw()
{
    static int first = 1;
    if (first) {
        AutoArrange();
        first = 0;
    }
    Fl_Scroll::draw();
}


// private

void GridBrowser::RearrangeChildren(int x, int y, int w, int h)
{
    int nchildren = children() - 2; // ignore child scrollbars
    if (nchildren < 1) {
        return;
    }

    int contentw = CalcContentWidth(w);

    int ncols = CalcColsNum(contentw);
    int thumbw = CalcThumbWidth(contentw, ncols);

    int contentx = x + (w - contentw) / 2;
    int contenty  = y;
    int thumbx = contentx;
    int thumby = contenty;

    for (int i = 0, c = 1; i < nchildren; i++, c++) {
        child(i)->resize(thumbx, thumby, thumbw, child(i)->h());

        if (c < ncols) {
            thumbx += thumbw + grid_cell_hpad;
        } else {
            thumby += child(i)->h() + grid_cell_vpad;
            thumbx = contentx;
            c = 0;
        }
    }
}

int GridBrowser::CalcContentWidth(int w)
{
    if (w >= 2256) {
        return 2256;
    } else if (w >= 601) {
        return w - grid_pad * 2;
    } else if (w >= 496 || w <= 320) {
        return w;
    } else if (w > 320) {
        return 320;
    }

    return w;
}

int GridBrowser::CalcColsNum(int w)
{
    if (w >= 1680) {
        return 5;
    } else if (w >= 1024) {
        return 4;
    } else if (w >= 768) {
        return 3;
    } else if (w >= 496) {
        return 2;
    } else {
        return 1;
    }
}

int GridBrowser::CalcThumbWidth(int w, int ncols)
{
    if (ncols < 2) {
        return w;
    }

    w -= grid_cell_hpad * (ncols - 1); // minus separators total width
    w = static_cast<int>(w / ncols);

    return w;
}

void GridBrowser::resize(int x, int y, int w, int h)
{
    RearrangeChildren(x, y, w, h);
    Fl_Scroll::resize(x, y, w, h);
}
